package com.onlinelearn.content.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.onlinelearn.base.exception.OnlineLearnException;
import com.onlinelearn.base.model.PageParams;
import com.onlinelearn.base.model.PageResult;
import com.onlinelearn.content.mapper.*;
import com.onlinelearn.content.model.dto.AddCourseDto;
import com.onlinelearn.content.model.dto.CourseBaseInfoDto;
import com.onlinelearn.content.model.dto.EditCourseDto;
import com.onlinelearn.content.model.dto.QueryCourseParamsDto;
import com.onlinelearn.content.model.po.*;
import com.onlinelearn.content.service.CourseBaseInfoService;
import com.onlinelearn.content.service.CourseMarketService;
import io.swagger.annotations.OAuth2Definition;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;

@Service
public class CourseBaseInfoServiceImpl implements CourseBaseInfoService {
    @Autowired
    CourseBaseMapper courseBaseMapper;
    @Autowired
    CourseMarketMapper courseMarketMapper;
    @Autowired
    CourseCategoryMapper courseCategoryMapper;
    @Autowired
    CourseMarketServiceImpl courseMarketService;
    @Autowired
    TeachplanMapper teachplanMapper;
    @Autowired
    TeachplanMediaMapper teachplanMediaMapper;
    @Autowired
    CourseTeacherMapper courseTeacherMapper;

    @Override
    public PageResult<CourseBase> queryCourseBaseList(Long companyId, PageParams pageParams, @RequestBody QueryCourseParamsDto queryCourseParamsDto) {
        LambdaQueryWrapper<CourseBase> courseBaseQueryWrapper = new LambdaQueryWrapper<>();

//        boolean condition, R column, Object val
//        模糊查询内容名称
        courseBaseQueryWrapper.like(StringUtils.isNotEmpty(queryCourseParamsDto.getCourseName()),CourseBase::getName,queryCourseParamsDto.getCourseName());
//      精确查询审核状态
        courseBaseQueryWrapper.eq(StringUtils.isNotEmpty(queryCourseParamsDto.getAuditStatus()),CourseBase::getAuditStatus,queryCourseParamsDto.getAuditStatus());
//      精确查询内容
        courseBaseQueryWrapper.eq(StringUtils.isNotEmpty(queryCourseParamsDto.getPublishStatus()),CourseBase::getStatus,queryCourseParamsDto.getPublishStatus());
        //机构id
        courseBaseQueryWrapper.eq(CourseBase::getCompanyId,companyId);

        Page<CourseBase> courseBaseMapperPage = new Page<>(pageParams.getPageNo(), pageParams.getPageSize());
        //        E page, @Param("ew") Wrapper<T> queryWrapper
        Page<CourseBase> courseBasePage = courseBaseMapper.selectPage(courseBaseMapperPage, courseBaseQueryWrapper);
        List<CourseBase> records = courseBasePage.getRecords();
        long total = courseBasePage.getTotal();

        PageResult<CourseBase> objectPageResult = new PageResult<>(records,total,pageParams.getPageNo(),pageParams.getPageSize());
        return objectPageResult;
    }

    @Override
    @Transactional
    public CourseBaseInfoDto createCourseBase(Long companyId, AddCourseDto dto) {
//        添加校验
        //合法性校验
//        if (StringUtils.isBlank(dto.getName())) {
////            throw new RuntimeException("课程名称为空");
//            OnlineLearnException.cast("课程名称为空!");
//        }
//
//        if (StringUtils.isBlank(dto.getMt())) {
//            throw new RuntimeException("课程分类为空");
//        }
//
//        if (StringUtils.isBlank(dto.getSt())) {
//            throw new RuntimeException("课程分类为空");
//        }
//
//        if (StringUtils.isBlank(dto.getGrade())) {
//            throw new RuntimeException("课程等级为空");
//        }
//
//        if (StringUtils.isBlank(dto.getTeachmode())) {
//            throw new RuntimeException("教育模式为空");
//        }
//
//        if (StringUtils.isBlank(dto.getUsers())) {
//            throw new RuntimeException("适应人群为空");
//        }
//
//        if (StringUtils.isBlank(dto.getCharge())) {
//            throw new RuntimeException("收费规则为空");
//        }
//        1.向课程基础信息表中添加数据
        CourseBase courseBase = new CourseBase();
        BeanUtils.copyProperties(dto,courseBase);
//        设置机构id
        courseBase.setCompanyId(companyId);
        //设置审核状态
        courseBase.setAuditStatus("202002");
        //设置发布状态
        courseBase.setStatus("203001");
//        设置创建时间
        courseBase.setCreateDate(LocalDateTime.now());

        int i1 = courseBaseMapper.insert(courseBase);
        Long courseId = courseBase.getId();
//        2.向营销表中添加数据
        CourseMarket courseMarket = new CourseMarket();
        BeanUtils.copyProperties(dto,courseMarket);
//        给营销表设置课程id
        courseMarket.setId(courseBase.getId());
        //收费规则
        String charge = dto.getCharge();

        //收费课程必须写价格且价格大于0
        if(charge.equals("201001")){
            Float price = dto.getPrice();
            if(price == null || price.floatValue()<=0){
                throw new RuntimeException("课程设置了收费价格不能为空且必须大于0");
            }
        }
        int i2 = courseMarketMapper.insert(courseMarket);
        if(i1 <= 0 || i2 <= 0){
            throw new RuntimeException("添加课程失败!");
        }

        return getCourseBaseInfo(courseId);
    }
    //根据课程id查询课程基本信息，包括基本信息和营销信息
    public CourseBaseInfoDto getCourseBaseInfo(Long courseId){

        CourseBase courseBase = courseBaseMapper.selectById(courseId);
        CourseMarket courseMarket = courseMarketMapper.selectById(courseId);

        if(courseBase == null){
            return null;
        }
        CourseBaseInfoDto courseBaseInfoDto = new CourseBaseInfoDto();
        BeanUtils.copyProperties(courseBase,courseBaseInfoDto);
        if(courseMarket != null){
            BeanUtils.copyProperties(courseMarket,courseBaseInfoDto);
        }

        //查询分类名称
        CourseCategory courseCategoryBySt = courseCategoryMapper.selectById(courseBase.getSt());
        courseBaseInfoDto.setStName(courseCategoryBySt.getName());
        CourseCategory courseCategoryByMt = courseCategoryMapper.selectById(courseBase.getMt());
        courseBaseInfoDto.setMtName(courseCategoryByMt.getName());

        return courseBaseInfoDto;

    }

    @Transactional
    @Override
    public CourseBaseInfoDto updateCourseBase(Long companyId,EditCourseDto dto) {

        //业务规则校验，本机构只允许修改本机构的课程
        //课程id
        Long courseId = dto.getId();
        validateCompanyId(companyId,courseId);
        CourseBase courseBase_u = courseBaseMapper.selectById(courseId);

        //封装数据
        //将请求参数拷贝到待修改对象中
        BeanUtils.copyProperties(dto,courseBase_u);
        courseBase_u.setChangeDate(LocalDateTime.now());
        //更新到数据库
        int i = courseBaseMapper.updateById(courseBase_u);

        //查询课程营销信息
        CourseMarket courseMarket = courseMarketMapper.selectById(courseId);
        if(courseMarket==null){
            courseMarket = new CourseMarket();
        }

        //判断是否收费
        String charge = dto.getCharge();
        if(charge.equals("201001")){
            Float price = dto.getPrice();
            if(price == null || price.floatValue()<=0){
                OnlineLearnException.cast("课程设置了收费价格不能为空且必须大于0");
            }
        }

        //将dto中的课程营销信息拷贝至courseMarket对象中
        BeanUtils.copyProperties(dto,courseMarket);

        boolean save = courseMarketService.saveOrUpdate(courseMarket);

        return getCourseBaseInfo(courseId);
    }
//Spring框架的事务基础架构代码将默认地 只 在抛出运行时和unchecked exceptions时才标识事务回滚。
// 也就是说，当抛出个RuntimeException 或其子类例的实例时。（Errors 也一样 - 默认地 - 标识事务回滚。）
// 从事务方法中抛出的Checked exceptions将 不 被标识进行事务回滚。
//    1 让checked例外也回滚：在整个方法前加上 @Transactional(rollbackFor=Exception.class)
//2 让unchecked例外 不 回滚：@Transactional(notRollbackFor=RunTimeException.class)

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteCourseBase(Long companyId,Long courseId) {
        validateCompanyId(companyId,courseId);
//        删除课程基本信息
        courseBaseMapper.deleteById(courseId);
//      删除课程营销信息
        LambdaQueryWrapper<CourseMarket> courseMarketLambdaQueryWrapper = new LambdaQueryWrapper<>();
        courseMarketLambdaQueryWrapper.eq(StringUtils.isNotEmpty(String.valueOf(courseId)),CourseMarket::getId,courseId);
        courseMarketMapper.delete(courseMarketLambdaQueryWrapper);
//        删除课程计划
        LambdaQueryWrapper<Teachplan> teachplanLambdaQueryWrapper = new LambdaQueryWrapper<>();
        teachplanLambdaQueryWrapper.eq(StringUtils.isNotEmpty(String.valueOf(courseId)),Teachplan::getCourseId,courseId);
        teachplanMapper.delete(teachplanLambdaQueryWrapper);
//        删除课程教师
        LambdaQueryWrapper<CourseTeacher> courseTeacherLambdaQueryWrapper = new LambdaQueryWrapper<>();
        courseTeacherLambdaQueryWrapper.eq(StringUtils.isNotEmpty(String.valueOf(courseId)),CourseTeacher::getCourseId,courseId);
        courseTeacherMapper.delete(courseTeacherLambdaQueryWrapper);
    }

    private void validateCompanyId(Long companyId,Long courseId){
        CourseBase courseBase_u = courseBaseMapper.selectById(courseId);
        if(courseBase_u==null){
            OnlineLearnException.cast("课程信息不存在");
        }
        if(!companyId.equals(courseBase_u.getCompanyId())){
            OnlineLearnException.cast("本机构只允许修改本机构的课程");
        }
    }
}
